package com.example.mtblog.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.example.mtblog.common.Result;
import com.example.mtblog.tool.FileUploadUtils;
import com.example.mtblog.tool.StrUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;


@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${mtblog.ip}")
     String ip;


    /**
    * @description: 拼接后缀名
    * @author MT
    * @date 2023/11/1 18:12
    */

    public  String splicingSuffixNames(String  mimeType , String name , String type) throws IOException {

        if(type.equals("image")){
            if(name.endsWith(".jpg") || name.endsWith(".png") || name.endsWith(".gif") || name.endsWith(".wbmp")|| name.endsWith(".webp")){
                return  name;
            }
;
            return name + mimeType;
        }

        return name;
    }
    @CrossOrigin
    @PostMapping(value = "/upload/{type}/{detail}")
    public Result<?> upload(@RequestPart(value = "file", required = false) MultipartFile file,
                            @PathVariable String type,
                            @PathVariable String detail) throws IOException {

        try {
            if (file == null)
                return Result.error("文件为空");


            String mimeType = Objects.requireNonNull(file.getContentType()).replace("/",".");


            String originalFilename = file.getOriginalFilename();//获取源文件的名称
            originalFilename = splicingSuffixNames(mimeType,originalFilename,type);

            String flag = IdUtil.fastSimpleUUID();//定义唯一标识
            String rootFilePath = "";
            rootFilePath = System.getProperty("user.dir") + "/files/" + type + "/" + detail + "/" + flag + originalFilename;

            File rootFile = new File(rootFilePath);
            if (!rootFile.getParentFile().exists()) {
                rootFile.getParentFile().mkdirs();
            }




            FileUtil.writeBytes(file.getBytes(), rootFilePath);



            return Result.success(ip + "/file/getFile/" + type + "/" + detail + "/" + flag + originalFilename);  // 返回结果 url
        }catch (Exception e){
            String error = "error in FileController/upload \n" + e;
            System.out.println(error);
            return Result.error(error);
        }
    }

    @GetMapping("/getFile/{type}/{detail}/{flag}")
    public void getFiles(@PathVariable String flag, @PathVariable String type, @PathVariable String detail,
                         HttpServletRequest request,
                         HttpServletResponse response) {


        String fileName = System.getProperty("user.dir") + "/files/" + type + "/" + detail + "/" + flag;   //获取视频

        try {
            if (StrUtil.isNotEmpty(fileName)) {
//                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(flag, "UTF-8"));

                Path filePath = Paths.get(fileName);
                String mimeType = Files.probeContentType(filePath);


                if (mimeType != null && !mimeType.isEmpty()) {
                    response.setContentType(mimeType);
                }

//                response.setContentType("application/octet-stream");
                if (mimeType != null && mimeType.equals("video/mp4")) {
                    File file = new File(fileName);

                    String rangeString = request.getHeader("Range");
                    long range = Long.parseLong(rangeString.substring(rangeString.indexOf("=") + 1, rangeString.indexOf("-")));
                    response.setContentLength(Math.toIntExact(file.length()));
                    response.setHeader("Content-Range", String.valueOf(range + (file.length() - 1)));
                    response.setHeader("Accept-Ranges", "bytes");

                }

                //设置Access-Control-Expose-Headers避免前端调用获取Content-Disposition出现Refused to get unsafe header异常
                response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));



                byte[] bytes = FileUtil.readBytes(fileName);  // 通过文件的路径读取文件字节流
                OutputStream os = response.getOutputStream();   // 通过输出流返回文件


                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println(e + "getfile");
        }
    }

    @CrossOrigin
    @PostMapping(value = "/uploadToQiniu/{type}/{detail}")
    public Result<?> uploadImageByQiniu(
                            @RequestPart(value = "file", required = false) MultipartFile file,
                            @PathVariable String type,
                            @PathVariable String detail) throws IOException {


        if (file == null)
            return Result.error("文件为空");

        String originalFilename = file.getOriginalFilename();//获取源文件的名称
        String flag = IdUtil.fastSimpleUUID();//定义唯一标识
        String filename  = "files/" + type + "/" + detail + "/" + flag + originalFilename;

       return FileUploadUtils.uploadImageToQiniu(file,filename);

    }
}



